/**
 * 用于存放当前角色所包含的权限
 * @type {*[]}
 */
let baseInfoAuthorityIds = [];

/**
 * 用于存放当前角色所包含的菜单权限，存放菜单id
 * @type {*[]}
 */
let baseInfoPermissionMenuIds = [];

/**
 * 用于存放当前角色所包含的按钮权限，存放按钮id
 * @type {*[]}
 */
let baseInfoPermissionButtonIds = [];

/**
 * 显示提示信息
 * @param type
 * @param message
 */
function showAlerts(type, message) {
    let alertDiv = $("#alertTemplate").clone();
    if (type == "error") {
        alertDiv.addClass("alert-danger");
    } else if (type == "warring") {
        alertDiv.addClass("alert-warning");
    }
    alertDiv.css("display", "block");
    alertDiv.find("span").text(message);

    $("#alertTemplate").after(alertDiv);

    setTimeout(function () {
        alertDiv.remove();
    }, 5000);
}

/**
 * 选择搜索类型
 * @param type
 */
function selectType(tag) {
    let li = $(tag);
    $(".select-type-wrap").attr("select-type-value", li.attr("search-type"));
    $(".select-type-btn .type-text").text(li.find("a").text());
}

/**
 * 根据角色信息显示基本信息面板
 * @param role
 */
function showBaseInfoByRole(role) {
    $(".base-info").attr("base-info-type", "role");
    $(".base-info").attr("base-info-id", role.id);


    baseInfoAuthorityIds = [];
    $.ajax({
        type: 'GET',
        async: false,
        url: "/service/authorize/authority/findByRoleId/" + role.id,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            for (let i = 0; i < data.length; i++) {
                baseInfoAuthorityIds.push(data[i].id);
            }
        }
    });

    baseInfoPermissionMenuIds = [];
    $.ajax({
        type: 'GET',
        async: false,
        url: "/service/authorize/menu/findByRoleId/" + role.id,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            for (let i = 0; i < data.length; i++) {
                baseInfoPermissionMenuIds.push(data[i].id);
            }
        }
    });


    baseInfoPermissionButtonIds = [];
    $.ajax({
        type: 'GET',
        async: false,
        url: "/service/authorize/button/findByRoleId/" + role.id,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            for (let i = 0; i < data.length; i++) {
                baseInfoPermissionButtonIds.push(data[i].id);
            }
        }
    });


    $(".authorize-component .base-info .panel-title").text(role.name);
    $(".authorize-component .base-info .role .id-value").text(role.id);

    $(".authorize-component .base-info .role .name-value").text(role.name);

    $(".authorize-component .base-info .role .description-value").text(role.description);

    $(".authorize-component .base-info").css("display", "block");
    $(".authorize-component .base-info .role").css("display", "block");
    $(".authorize-component .base-info .user").css("display", "none");

    $(".authorize-component .authority-list").empty();
    $(".authorize-component .front-element-forest").empty();

    $(".authorize-component .microservice-list lable.active").removeClass("active");
    $(".authorize-component .front-app-list lable.active").removeClass("active");

    if (!$(".authorize-component .authorize-panel").hasClass("show")) {
        $(".authorize-component .authorize-panel").addClass("show");
    }
}

/**
 * 查询微服务列表
 */
function queryMicroserviceList() {
    $.ajax({
        type: 'GET',
        url: "/service/authorize/microservice/all",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            for (let i = 0; i < data.length; i++) {
                let microservice = data[i];

                let label = $("<lable></lable>");
                label.addClass("btn");
                label.addClass("btn-primary");
                label.click(function () {
                    findByMicroservice(microservice.id);
                });

                let input = $("<input/>");
                input.attr("type", "radio");
                input.attr("name", "options");

                let span = $("<span></span>");
                span.text(microservice.name);

                label.append(input);
                label.append(span);

                $(".authorize-component .microservice-list").append(label);
            }
        }
    });
}


/**
 * 查询子菜单
 * @param menuPanel 父级菜单
 */
function queryMenus(menuPanel) {
    let menuId = menuPanel.attr("menu-id");
    $.ajax({
        type: "GET",
        url: "/service/authorize/menu/findMenusByParent/" + menuId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            menuPanel.addClass("queried");
            let menuIcon = menuPanel.children(".self").children(".menu-icon");
            menuIcon.addClass("open");
            let childrenDiv = menuPanel.children(".children");
            childrenDiv.addClass("show");

            for (let i = 0; i < data.length; i++) {

                let li = $("<li></li>");

                let childMenu = data[i];
                let childMenuPanel = $(".authorize-component .templates .menu-panel").clone();

                if (baseInfoPermissionMenuIds.indexOf(childMenu.id) != -1) {
                    childMenuPanel.children(".self").addClass("has-permission");
                    childMenuPanel.find(".grant-authority-button").addClass("inactive");
                }
                else {
                    childMenuPanel.find(".cancel-authority-button").addClass("inactive");
                }

                if (childMenu.type == 0) {
                    childMenuPanel.find(".menu-icon").addClass("menu");
                    childMenuPanel.attr("type", "menu");
                } else {
                    childMenuPanel.find(".menu-icon").addClass("menu-folder");
                    childMenuPanel.attr("type", "menu-folder");
                    childMenuPanel.children(".self").children(".operation-button-wrap").addClass("menu-folder");
                }
                childMenuPanel.attr("menu-id", childMenu.id);
                childMenuPanel.find(".menu-code").text(childMenu.code);
                childMenuPanel.find(".menu-name").text(childMenu.name);

                childMenuPanel.find(".menu-icon").click(function () {
                    handleMenuIconClick(childMenuPanel);
                });

                childMenuPanel.find(".grant-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    authorizeMenu(childMenuPanel)
                });

                childMenuPanel.find(".cancel-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    cancelMenuAuthority(childMenuPanel);
                });

                li.append(childMenuPanel);
                childrenDiv.children("ul").append(li);
            }

        }
    });
}


/**
 * 查询按钮
 * @param menuPanel 父级菜单
 */
function queryButtons(menuPanel) {
    let menuId = menuPanel.attr("menu-id");
    $.ajax({
        type: "GET",
        url: "/service/authorize/button/findButtonsByMenu/" + menuId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            menuPanel.addClass("queried");
            let menuIcon = menuPanel.children(".self").children(".menu-icon");
            menuIcon.addClass("open");
            let childrenDiv = menuPanel.children(".children");
            childrenDiv.addClass("show");

            for (let i = 0; i < data.length; i++) {

                let li = $("<li></li>");

                let button = data[i];
                let buttonPanel = $(".authorize-component .templates .button-panel").clone();

                if (baseInfoPermissionButtonIds.indexOf(button.id) != -1) {
                    buttonPanel.children(".self").addClass("has-permission");
                    buttonPanel.find(".grant-authority-button").addClass("inactive");
                }
                else {
                    buttonPanel.find(".cancel-authority-button").addClass("inactive");
                }

                buttonPanel.attr("button-id", button.id);
                buttonPanel.attr("type", "button");
                buttonPanel.find(".button-code").text(button.code);
                buttonPanel.find(".button-name").text(button.name);

                buttonPanel.find(".grant-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    authorizeButton(buttonPanel)
                });

                buttonPanel.find(".cancel-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    cancelButtonAuthority(buttonPanel);
                });

                li.append(buttonPanel);
                childrenDiv.children("ul").append(li);
            }
        }
    });
}

/**
 *
 * 为菜单icon增加事件处理
 *
 * @param menuPanel
 */
function handleMenuIconClick(menuPanel) {
    let menuIcon = menuPanel.children(".self").children(".menu-icon");
    let childrenDiv = menuPanel.children(".children");
    if (!menuIcon.hasClass("open") && !menuPanel.hasClass("queried")) {
        if (menuIcon.hasClass("menu")) {
            queryButtons(menuPanel)
        } else {
            queryMenus(menuPanel);
        }
    } else if (!menuIcon.hasClass("open")) {
        menuIcon.addClass("open");
        childrenDiv.addClass("show");
    } else if (menuIcon.hasClass("open")) {
        menuIcon.removeClass("open");
        childrenDiv.removeClass("show");
    }
}


/**
 * 查询根菜单
 * @param appId appId
 */
function queryRootMenus(appId) {
    $.ajax({
        type: "GET",
        url: "/service/authorize/menu/findRootMenuByApp/" + appId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            let frontElementForest = $(".authorize-component .front-element-forest");
            frontElementForest.empty();

            for (let i = 0; i < data.length; i++) {
                let menu = data[i];
                let menuPanel = $(".authorize-component .templates .menu-panel").clone();

                if (baseInfoPermissionMenuIds.indexOf(menu.id) != -1) {
                    menuPanel.children(".self").addClass("has-permission");
                    menuPanel.find(".grant-authority-button").addClass("inactive");
                }
                else {
                    menuPanel.find(".cancel-authority-button").addClass("inactive");
                }

                if (menu.type == 0) {
                    menuPanel.find(".menu-icon").addClass("menu");
                    menuPanel.attr("type", "menu");
                } else {
                    menuPanel.find(".menu-icon").addClass("menu-folder");
                    menuPanel.attr("type", "menu-folder");
                    menuPanel.children(".self").children(".operation-button-wrap").addClass("menu-folder");
                }

                menuPanel.attr("menu-id", menu.id);
                menuPanel.find(".menu-code").text(menu.code);
                menuPanel.find(".menu-name").text(menu.name);

                menuPanel.find(".menu-icon").click(function () {
                    handleMenuIconClick(menuPanel);
                });

                menuPanel.find(".grant-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    authorizeMenu(menuPanel)
                });

                menuPanel.find(".cancel-authority-button").click(function () {
                    if ($(this).hasClass(".inactive")) {
                        return;
                    }
                    cancelMenuAuthority(menuPanel);
                });

                frontElementForest.append(menuPanel);
            }
        }
    });
}

/**
 * 菜单权限授予成功
 * @param menuPanel
 */
function authorizeMenuSuccess(menuPanel) {
    menuPanel.children(".self").addClass("has-permission");
    let menuId = menuPanel.attr("menu-id");
    baseInfoPermissionMenuIds.push(parseInt(menuId));
    menuPanel.children(".self").find(".grant-authority-button").addClass("inactive");
    menuPanel.children(".self").find(".cancel-authority-button").removeClass("inactive");
}

/**
 * 按钮权限授予成功
 * @param menuPanel
 */
function authorizeButtonSuccess(buttonPanel) {
    buttonPanel.children(".self").addClass("has-permission");
    let buttonId = buttonPanel.attr("button-id");
    baseInfoPermissionButtonIds.push(parseInt(buttonId));
    buttonPanel.children(".self").find(".grant-authority-button").addClass("inactive");
    buttonPanel.children(".self").find(".cancel-authority-button").removeClass("inactive");
}

/**
 * 菜单权限取消成功
 * @param menuPanel
 */
function cancelMenuAuthoritySuccess(menuPanel) {
    menuPanel.children(".self").removeClass("has-permission");
    let menuId = menuPanel.attr("menu-id");
    let index = baseInfoPermissionMenuIds.indexOf(parseInt(menuId));
    baseInfoPermissionMenuIds.splice(index, 1);
    menuPanel.children(".self").find(".grant-authority-button").removeClass("inactive");
    menuPanel.children(".self").find(".cancel-authority-button").addClass("inactive");
}

/**
 * 按钮权限取消成功
 * @param buttonPanel
 */
function cancelButtonAuthoritySuccess(buttonPanel) {
    buttonPanel.children(".self").removeClass("has-permission");
    let buttonId = buttonPanel.attr("button-id");
    let index = baseInfoPermissionButtonIds.indexOf(parseInt(buttonId));
    baseInfoPermissionButtonIds.splice(index, 1);
    buttonPanel.children(".self").find(".grant-authority-button").removeClass("inactive");
    buttonPanel.children(".self").find(".cancel-authority-button").addClass("inactive");
}

/**
 *
 * 授予菜单权限
 *
 * @param menuPanel
 */
function authorizeMenu(menuPanel) {
    let menuId = menuPanel.attr("menu-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        let requestData = {
            roleId: $(".base-info").attr("base-info-id"),
            menuId: menuId
        };
        $.ajax({
            type: 'POST',
            url: "/service/authorize/role/authorizeMenu",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: requestData,
            success: function () {
                authorizeMenuSuccess(menuPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'POST',
            url: "/service/authorize/user/authorizeMenu",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                menuId: menuId
            },
            success: function () {
                authorizeMenuSuccess(menuPanel);
            }
        });
    }
}

/**
 *
 * 授予按钮权限
 *
 * @param buttonPanel
 */
function authorizeButton(buttonPanel) {
    let buttonId = buttonPanel.attr("button-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        let requestData = {
            roleId: $(".base-info").attr("base-info-id"),
            buttonId: buttonId
        };
        $.ajax({
            type: 'POST',
            url: "/service/authorize/role/authorizeButton",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: requestData,
            success: function () {
                authorizeButtonSuccess(buttonPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'POST',
            url: "/service/authorize/user/authorizeButton",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                buttonId: buttonId
            },
            success: function () {
                authorizeButtonSuccess(buttonPanel);
            }
        });
    }
}

/**
 *
 * 取消菜单权限
 *
 * @param menuPanel
 */
function cancelMenuAuthority(menuPanel) {
    let menuId = menuPanel.attr("menu-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        let requestData = {
            roleId: $(".base-info").attr("base-info-id"),
            menuId: menuId
        };
        $.ajax({
            type: 'DELETE',
            url: "/service/authorize/role/cancelMenuAuthority",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: requestData,
            success: function () {
                cancelMenuAuthoritySuccess(menuPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'DELETE',
            url: "/service/authorize/user/cancelMenuAuthority",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                menuId: menuId
            },
            success: function () {
                cancelMenuAuthoritySuccess(menuPanel);
            }
        });
    }
}

/**
 *
 * 取消按钮权限
 *
 * @param buttonPanel
 */
function cancelButtonAuthority(buttonPanel) {
    let buttonId = buttonPanel.attr("button-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        let requestData = {
            roleId: $(".base-info").attr("base-info-id"),
            buttonId: buttonId
        };
        $.ajax({
            type: 'DELETE',
            url: "/service/authorize/role/cancelButtonAuthority",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: requestData,
            success: function () {
                cancelButtonAuthoritySuccess(buttonPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'DELETE',
            url: "/service/authorize/user/cancelButtonAuthority",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                buttonId: buttonId
            },
            success: function () {
                cancelButtonAuthoritySuccess(buttonPanel);
            }
        });
    }
}

/**
 *
 *  查询前台APP列表
 *
 */
function queryFrontAppList() {
    $.ajax({
        type: 'GET',
        url: "/service/authorize/app/all",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            for (let i = 0; i < data.length; i++) {
                let app = data[i];

                let label = $("<lable></lable>");
                label.addClass("btn");
                label.addClass("btn-primary");
                label.click(function () {
                    queryRootMenus(app.id);
                });

                let input = $("<input/>");
                input.attr("type", "radio");
                input.attr("name", "options");

                let span = $("<span></span>");
                span.text(app.name);

                label.append(input);
                label.append(span);

                $(".authorize-component .front-app-list").append(label);
            }
        }
    });
}

/**
 * 根据角色列表显示suggestion
 * @param roles
 */
function showSuggestionByRoles(roles) {
    $(".search-suggestion-div").empty();
    for (let i = 0; i < roles.length; i++) {
        let role = roles[i];

        let roleSuggestionDiv = $("<div/>");
        roleSuggestionDiv.addClass("search-suggestion-line");
        roleSuggestionDiv.click(function () {
            $(".search-suggestion-div").empty();
            showBaseInfoByRole(role);
        });

        let idDiv = $("<div/>");
        idDiv.addClass("suggestion-element");
        idDiv.addClass("id-element");
        idDiv.text(role.id);
        roleSuggestionDiv.append(idDiv);

        let nameDiv = $("<div/>");
        nameDiv.addClass("suggestion-element");
        nameDiv.addClass("name-element");
        nameDiv.text(role.name);
        roleSuggestionDiv.append(nameDiv);

        let descriptionDiv = $("<div/>");
        descriptionDiv.addClass("suggestion-element");
        descriptionDiv.addClass("role-description-element");
        descriptionDiv.text(role.description);
        roleSuggestionDiv.append(descriptionDiv);

        $(".search-suggestion-div").append(roleSuggestionDiv);
    }
}

/**
 * 授权
 * @param authorityId
 */
function authorize(authorityPanel) {
    let authorityId = authorityPanel.attr("authority-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        let requestData = {
            roleId: $(".base-info").attr("base-info-id"),
            authorityIds: [authorityId]
        };
        $.ajax({
            type: 'POST',
            url: "/service/authorize/role/roleAuthorize",
            contentType: "application/json;charset=UTF-8",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: JSON.stringify(requestData),
            success: function () {
                authorizeSuccess(authorityPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'POST',
            url: "/service/authorize/user/authorize",
            headers: {
                Authorization: JwtTokenUtils.getBearerHeader()
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                authorityId: authorityId
            },
            success: function () {
                authorizeSuccess(authorityPanel);
            }
        });
    }
}

/**
 * 授权成功之后的逻辑
 * @param authorityPanel
 */
function authorizeSuccess(authorityPanel) {
    let authorityId = authorityPanel.attr("authority-id");
    baseInfoAuthorityIds.push(parseInt(authorityId));
    authorityPanel.removeClass("panel-danger");
    authorityPanel.addClass("panel-success");
    authorityPanel.find(".authorize-btn").css("display", "none");
    authorityPanel.find(".cancel-authority-btn").css("display", "block");
}

/**
 * 取消权限
 * @param authorityId
 */
function cancelAuthorities(authorityPanel) {
    let authorityId = authorityPanel.attr("authority-id");
    let baseInfoType = $(".base-info").attr("base-info-type");

    if (baseInfoType == "role") {
        $.ajax({
            type: 'DELETE',
            url: "/service/authorize/role/cancelAuthorities",
            contentType: "application/json;charset=UTF-8",
            headers: {
                token: localStorage.getItem("token")
            },
            data: JSON.stringify({
                roleId: $(".base-info").attr("base-info-id"),
                authorityIds: [authorityId]
            }),
            success: function () {
                cancelAuthoritiesSuccess(authorityPanel);
            }
        });
    } else if (baseInfoType == "user") {
        $.ajax({
            type: 'POST',
            url: "/service/authorize/user/authorize",
            headers: {
                token: localStorage.getItem("token")
            },
            data: {
                userId: $(".base-info").attr("base-info-id"),
                authorityId: authorityId
            },
            success: function () {
                cancelAuthoritiesSuccess(authorityPanel);
            }
        });
    }
}

/**
 * 取消权限成功后的执行逻辑
 * @param authorityPanel
 */
function cancelAuthoritiesSuccess(authorityPanel) {
    let authorityId = authorityPanel.attr("authority-id");
    let index = baseInfoAuthorityIds.indexOf(parseInt(authorityId));
    baseInfoAuthorityIds.splice(index, 1);
    authorityPanel.removeClass("panel-success");
    if (!authorityPanel.hasClass("panel-primary")) {
        authorityPanel.addClass("panel-danger");
    }
    authorityPanel.find(".authorize-btn").css("display", "block");
    authorityPanel.find(".cancel-authority-btn").css("display", "none");
}

/**
 * 查询基本信息
 */
function searchBaseInfo() {
    let searchText = $(".search-text").val();
    if (typeof searchText == "undefined" || searchText == undefined || searchText == null || searchText.trim() == "") {
        showAlerts("error", "请先输入搜索的角色（用户）名");
        return;
    }

    $.ajax({
        type: 'GET',
        url: "/service/authorize/role/findRolesByNameLike",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            name: searchText
        },
        success: function (data) {
            console.log(data);
            if (data.length == 0) {
                showAlerts("warring", "No results found");
            } else if (data.length == 1) {
                let role = data[0];
                showBaseInfoByRole(role);
            } else if (data.length > 1) {
                showSuggestionByRoles(data);
            }
        }
    });

}

/**
 * 根据微服务id查询服务列表
 * @param microserviceId
 */
function findByMicroservice(microserviceId) {
    let authorityListDiv = $(".authorize-component .authority-list");
    authorityListDiv.empty();
    $.ajax({
        type: 'GET',
        url: "/service/authorize/authority/findByMicroservice/" + microserviceId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            console.log(data);
            for (let i = 0; i < data.length; i++) {
                let authority = data[i];

                let authorityDiv = $(".authorize-component  #authorityTemplate").clone();
                authorityDiv.removeAttr("id");
                authorityDiv.attr("authority-id", authority.id);
                authorityDiv.css("display", "block");
                authorityDiv.find(".panel-title").text(authority.uri);
                authorityDiv.find(".authorize-btn").click(function () {
                    authorize(authorityDiv);
                }
                );
                authorityDiv.find(".cancel-authority-btn").click(
                    function () {
                        cancelAuthorities(authorityDiv);
                    }
                );

                if (baseInfoAuthorityIds.includes(authority.id)) {
                    authorityDiv.addClass("panel-success");
                    authorityDiv.find(".authorize-btn").css("display", "none");
                } else {
                    authorityDiv.addClass("panel-danger");
                    authorityDiv.find(".cancel-authority-btn").css("display", "none");
                }

                authorityListDiv.append(authorityDiv);
            }
        }
    });
}

/**
 * 查询用户的角色列表
 */
function queryRoleList() {
    let userId = $(".authorize-component .base-info").attr("base-info-id");
    $.ajax({
        type: "GET",
        url: "/service/authorize/role/findRolesByUserId/" + userId,
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        success: function (data) {
            $(".authorize-component .role-list").empty();
            $(".authorize-component .role-list").addClass("expansion");
            if (!$(".authorize-component .role-list").hasClass("queried")) {
                $(".authorize-component .role-list").addClass("queried");
            }
            $(".authorize-component .role-list-show-button").addClass("open");
            for (let i = 0; i < data.length; i++) {
                let role = data[i];
                let rolePanel = $(".authorize-component .templates .role-panel").clone();
                rolePanel.attr("role-id", role.id);
                rolePanel.find(".role-id-div").text(role.id);
                rolePanel.find(".role-name-div").text(role.name);
                rolePanel.find(".role-description-div").text(role.description);
                rolePanel.find(".delete-role-button").click(function () {
                    $(".authorize-component .delete-confirm-window").modal('show');
                    $(".authorize-component .delete-confirm-window .delete-confirm-content").text("Are you sure you want to dismiss this role?");
                    $(".authorize-component .delete-confirm-window").find(".delete-confirm-btn").click(function () {
                        dismissRole(rolePanel);
                    });
                });
                $(".authorize-component .role-list").append(rolePanel);
            }
        }
    });
}


/**
 * 搜索角色
 */
function searchRoles() {
    let searchText = $(".authorize-component .search-role-input").val();
    $.ajax({
        type: 'GET',
        url: "/service/authorize/role/findRolesByNameLike",
        headers: {
            Authorization: JwtTokenUtils.getBearerHeader()
        },
        data: {
            name: searchText
        },
        success: function (data) {
            $(".authorize-component .search-role-list").empty();
            for (let i = 0; i < data.length; i++) {
                let role = data[i];
                let searchRolePanel = $(".authorize-component .templates .search-role-panel").clone();
                searchRolePanel.find(".search-role-id").attr("value", role.id);
                searchRolePanel.find(".role-name-div").text(role.name);
                searchRolePanel.find(".role-description-div").text(role.description);
                $(".authorize-component .search-role-list").append(searchRolePanel);
            }
        }
    });
}

/**
 * 页面启动完成事件
 *
 * 1.查询微服务列表
 * 2.搜索框增加键盘回车事件，回车执行搜索
 *
 */
$(document).ready(function () {
    queryMicroserviceList();

    queryFrontAppList();

    $(".authorize-component .search-text").keyup(
        function (event) {
            if (event.keyCode == "13") {
                searchBaseInfo();
            }
        }
    );

    $(".authorize-component .role-list-show-button").click(function () {
        if ($(this).hasClass("open")) {
            $(this).removeClass("open");
            $(".authorize-component .role-list").removeClass("expansion");
        } else if ($(".authorize-component .role-list").hasClass("queried")) {
            $(this).addClass("open");
            $(".authorize-component .role-list").addClass("expansion");
        } else {
            queryRoleList();
        }
    });

    $(".authorize-component .add-role-button").click(function () {
        $(".authorize-component .add-role-panel").addClass("show");
    });

    $(".authorize-component .add-role-panel .search-button").click(function () {
        searchRoles();
    });

    $(".authorize-component .add-role-panel .search-role-input").keyup(function (event) {
        if (event.keyCode == "13") {
            searchRoles();
        }
    });

    $(".authorize-component .add-role-panel .ok-button").click(function () {
        assignRole();
    });

    $(".authorize-component .add-role-panel .reset-button").click(function () {
        $(".authorize-component .add-role-panel input").val("");
        $(".authorize-component .add-role-panel textarea").val("");
        $(".authorize-component .add-role-panel .search-role-list").empty();
    });

    $(".authorize-component .add-role-panel .close-button").click(function () {
        $(".authorize-component .add-role-panel").removeClass("show");
    });

});